package com.cloudwave.trailends.ui;

import java.text.DecimalFormat;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.cloudwave.trailends.AppContext;
import com.cloudwave.trailends.Constants;
import com.cloudwave.trailends.R;
import com.cloudwave.trailends.compo.BaseActivity;
import com.cloudwave.trailends.domain.User;
import com.cloudwave.trailends.service.RidingService;
import com.cloudwave.trailends.service.SyncService;
import com.cloudwave.trailends.utils.DateUtils;
import com.cloudwave.trailends.utils.ImageUtils;
import com.cloudwave.trailends.widget.view.CustomDialog;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.bitmap.callback.DefaultBitmapLoadCallBack;

/**
 * 用户
 * 基准代码 500
 * @author 龙雪
 *
 */
public class UserActivity extends BaseActivity {
	private static final String TAG = "UserActivity";
	private DecimalFormat df = new DecimalFormat("#0.00");
	
	private ImageButton btnBack;
	private ImageButton btnOK;
	
	private TextView tvLoginDate;
	private TextView tvLogout;
//	private RoundedImageView ivAvatar;
	private ImageView ivAvatar;
	private TextView tvUserName;
	private TextView tvMileageCount;
	private TextView tvRidingLineCount;
	private TextView tvRidingTimeCount;
//	private TextView tvLinePointCount;
	
	private BitmapUtils bitmapUtils;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user);
		
        iniView();
        
        initData();
    }

	private void iniView() {
		btnBack = (ImageButton) findViewById(R.id.btnBack);
		btnOK = (ImageButton) findViewById(R.id.btnOK);
		tvLoginDate = (TextView) findViewById(R.id.tvLoginDate);
		ivAvatar = (ImageView) findViewById(R.id.ivAvatar);
		tvUserName = (TextView) findViewById(R.id.tvUserName);
		tvLogout = (TextView) findViewById(R.id.tvLogout);
		tvMileageCount = (TextView) findViewById(R.id.tvMileageCount);
		tvRidingLineCount = (TextView) findViewById(R.id.tvRidingLineCount);
		tvRidingTimeCount = (TextView) findViewById(R.id.tvRidingTimeCount);
//		tvLinePointCount = (TextView) findViewById(R.id.tvLinePointCount);
		btnOK.setVisibility(View.VISIBLE);
		
		btnBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				UserActivity.this.finish();
			}
		});
		btnOK.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
//				UserActivity.this.finish();
				editUserInfo();
			}
		});
		ivAvatar.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 这里可以实现点击查看大图的功能
			}
		});
		
		tvLogout.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				logout();
			}
		});
	}
	
	private void initData() {
		User u = ((AppContext) getApplication()).loadLoginUser();
		
		tvUserName.setText(u.getUserName());
		
		String regDate = "未知";
		if (u.getRegtime() != null) {
			regDate = DateUtils.formatDate(u.getRegtime());
		}
		
		String sFormat = getResources().getString(R.string.tv_login_date);  
		String sFinalDate = String.format(sFormat, regDate);  
		tvLoginDate.setText(sFinalDate);
		
		tvMileageCount.setText(String.valueOf(df.format(u.getTotalMileage() / 1000)));
		tvRidingLineCount.setText(String.valueOf(u.getTotalRidingLine()));
		
		String tFormat = getResources().getString(R.string.tv_riding_total_time);
		int[] time = DateUtils.duration(u.getTotalRidingTime() * 1000);
		String tFinalTime = String.format(tFormat, time[1], time[2]);
		tvRidingTimeCount.setText(tFinalTime);
//		tvLinePointCount.setText(String.valueOf(u.getTotalLinePoint()));
		
//		String avatarLocalUrl = ((AppContext) getApplication()).getAsString("user.avatarLocalUrl");
//		String avatarUrl = ((AppContext) getApplication()).getAsString("user.avatarUrl");
//		String avatar = TextUtils.isEmpty(avatarLocalUrl) ? avatarUrl : avatarLocalUrl;
		
		if ( u != null && !TextUtils.isEmpty(u.getAvatar()) ) {
			showAvatar(u.getAvatar());
		}
	}
	
	private void showAvatar(String avatar) {
		if (bitmapUtils == null) {
            bitmapUtils = new BitmapUtils(this.getApplicationContext());
        }
		bitmapUtils.configDefaultConnectTimeout(5000);
		bitmapUtils.configDefaultLoadFailedImage(R.drawable.avatar);
		bitmapUtils.display(ivAvatar, avatar, new DefaultBitmapLoadCallBack<ImageView>() {
			
			@Override
			public void onLoadStarted(ImageView container,
					String uri, BitmapDisplayConfig config) {
				super.onLoadStarted(container, uri, config);
				Log.v(TAG, "onLoadStarted");
			}
			@Override
			public void onLoading(ImageView container, String uri,
					BitmapDisplayConfig config, long total, long current) {
				super.onLoading(container, uri, config, total, current);
//					container.setImageResource(R.drawable.avatar);  //设置了这一行代码之后头像就不能正常显示了#BUG#
				Log.v(TAG, "onLoading");
			}
			@Override
			public void onLoadCompleted(ImageView container, String uri,
					Bitmap bitmap, BitmapDisplayConfig config,
					BitmapLoadFrom from) {
				super.onLoadCompleted(container, uri, bitmap, config, from);
//					fadeInDisplay(container, bitmap);
				fadeInDisplay(container, ImageUtils.toRoundCorner(bitmap, 80));
//			        container.setImageBitmap(ImageUtils.toRoundCorner(bitmap, 80));
		        
				Log.v(TAG, "onLoadCompleted");
			}

			@Override
			public void onLoadFailed(ImageView container, String uri,
					Drawable drawable) {
				container.setImageResource(R.drawable.avatar);
				Log.v(TAG, "onLoadFailed");
			}
			
		});
	}
	
	private void editUserInfo() {
		Intent intent = new Intent(UserActivity.this, UserInfoActivity.class);
		startActivityForResult(intent, 501);
	}
	
	private static final ColorDrawable TRANSPARENT_DRAWABLE = new ColorDrawable(android.R.color.transparent);
	
	private void fadeInDisplay(ImageView imageView, Bitmap bitmap) {
        final TransitionDrawable transitionDrawable =
                new TransitionDrawable(new Drawable[]{
                        TRANSPARENT_DRAWABLE,
                        new BitmapDrawable(imageView.getResources(), bitmap)
                });
        imageView.setImageDrawable(transitionDrawable);
        transitionDrawable.startTransition(500);
    }
	
	@Override
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if ( 1 == resultCode ) {
			User u = ((AppContext) getApplication()).loadLoginUser();
			if ( u != null && !TextUtils.isEmpty(u.getAvatar()) ) {
				showAvatar(u.getAvatar());
			}
		}
   }
	
	// 注销
	private void logout() {
		CustomDialog dialog = null;
		
		if ( RidingService.now_rlId != 0 ) {
			dialog = new CustomDialog(UserActivity.this, R.style.dialog_style
					, R.layout.dialog, R.string.dialog_riding_logout, false);
		} else if ( SyncService.isSyncing ) {
			dialog = new CustomDialog(UserActivity.this, R.style.dialog_style
					, R.layout.dialog, R.string.dialog_sync_logout, false);
		} else {
			dialog = new CustomDialog(UserActivity.this, R.style.dialog_style
					, R.layout.dialog, R.string.dialog_logout, new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					switch ( v.getId() ) {
					case R.id.confirm_btn:
						dealLogout();
						break;
					default:
			            break;
					}
				}
			});
		}
        dialog.show();
	}
	
	private void dealLogout() {
		User u = ((AppContext) getApplication()).loadLoginUser();
		((AppContext) getApplication()).put(Constants.CACHE_USER_NAME, u.getUserName());
		// 1. 清除账号缓存
		((AppContext) getApplication()).clearLoginUser();
		
		// 2.跳转到登录界面
		Intent intent = new Intent(UserActivity.this, SigninActivity.class);
		intent.putExtra("page", 1);
		startActivity(intent);
		// 3.销毁当前activity
		UserActivity.this.finish();
	}
}
